// 判断有没有登录参数，如果有，则请求用户信息
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const paramValue = urlParams.get('id');

if (sessionStorage.getItem("userId") == null) {
    sessionStorage.setItem("userId", 'NaN');
    location.href = `${sxport}public/HTML/index.html`;
} else if (sessionStorage.getItem("userId") != null && sessionStorage.getItem("userId") != paramValue) {
    location.href = `${sxport}public/HTML/index.html?id=${sessionStorage.getItem("userId")}`;
}

if (paramValue && paramValue != 'NaN') {
    fetchUserInfo(paramValue);
}

// 登录功能
$('#LD').click(function () {
    if (paramValue != 'NaN') return;
    toggleLoginRegister();
    setupRegister();
    setupLogin();
    ForgetPasswordError();
});

// 获取用户信息
function fetchUserInfo(id) {
    $.post(port + 'user', { paramValue: id }, function (data) {
        data = JSON.parse(data);
        if (data.code == 0) {
            showPrompt(data.module);
            return;
        }
        //showPrompt(data.module);
        $('#name').text(data.result[0].name);
        $('#LD').html(`<img src="${data.result[0].avatar}" >`);
    });
}

//清除所有input内容
function clearInput() {
    $('input[type="text"]').val('');
    $('input[type="password"]').val('');
}

// 切换登录,注册和忘记密码界面
function toggleLoginRegister() {
    $('#register').css('height', '100%');
    $('.close').click(function () {
        $('.loginBox').css('height', '0');
        $('#forgetPassword').css('height', '0');
        clearInput()
    });
    $('#SwitchLogin').click(function () {
        $('#login').css('height', '100%');
        $('#register').css('height', '0');
        $('#forgetPassword').css('height', '0');
        clearInput()
    });
    $('#SwitchRegister').click(function () {
        $('#login').css('height', '0');
        $('#forgetPassword').css('height', '0');
        $('#register').css('height', '100%');
        clearInput()
    });
    $('#ForgetPassword').click(function () {
        $('#login').css('height', '0');
        $('#register').css('height', '0');
        $('#Password').css('height', '100%');
        clearInput()
    })
}

//忘记密码
function ForgetPasswordError() {
    $('#FPB').click(function (e) {
        e.preventDefault();
        let account = $('#passwordUsername').val();
        let password = $('#FP').val();
        let rVC = $('#passwordVerificationCode').val();
        let errors = {
            username: $('#passwordUsernameError'),
            password: $('#ForgetPasswordError'),
            verificationCode: $('#passwordVerificationCodeError')
        };
        if (validateInput(account, password, rVC, errors)) {
            if (localStorage.getItem('verificationCode') != rVC) {
                showPrompt('验证码错误！');
                return;
            }
            ForgetP(account, password);
        }
    });
    // 发送验证码
    $('#passwordVerificationCodeBtn').click(function () {
        let account = $('#passwordUsername').val();
        let error = $('#passwordUsernameError');
        if (account == '') {
            error.text('用户名不能为空！');
        } else if (!isValidAccount(account)) {
            error.text('请输入正确的手机号或邮箱!!!');
        } else {
            error.text('');
            sendVerificationCode(account);
        }
    });
}

function ForgetP(account, password) {
    $.post(port + 'forgetPassword', { account, password }, function (data) {
        data = JSON.parse(data);
        if (data.code == 0) {
            showPrompt(data.module);
            return;
        }
        localStorage.removeItem('verificationCode');
        showPrompt(data.module);
        $('#Password').css('height', '0');
        $('#login').css('height', '100%');
        clearInput();
    });
}

// 注册账号
let flag = false;

function setupRegister() {
    $('#registerBtn').click(function (e) {
        e.preventDefault();
        let account = $('#registerUsername').val();
        let password = $('#registerPassword').val();
        let rVC = $('#registerVerificationCode').val();
        let errors = {
            username: $('#registerUsernameError'),
            password: $('#registerPasswordError'),
            verificationCode: $('#registerVerificationCodeError')
        };
        if (validateInput(account, password, rVC, errors)) {
            if (localStorage.getItem('verificationCode') != rVC) {
                showPrompt('验证码错误！');
                return;
            }
            registerUser(account, password);
        }
    });

    // 发送验证码
    $('#registerVerificationCodeBtn').click(function () {
        let account = $('#registerUsername').val();
        let error = $('#registerUsernameError');
        if (account == '') {
            error.text('用户名不能为空！');
        } else if (!isValidAccount(account)) {
            error.text('请输入正确的手机号或邮箱!!!');
        } else {
            error.text('');
            sendVerificationCode(account);
        }
    });
}

// 发送验证码函数
function sendVerificationCode(account) {
    let url = isValidPhone(account) ? port + 'phone' : port + 'email';
    $.post(url, { account }, function (data) {
        data = JSON.parse(data);
        if (data.code == 0) {
            showPrompt(data.module);
            $('.CAPTCHA').text('发送验证码');
            count = 60;
            flag = false;
            clearInterval(timer);
            return;
        }
        if (flag) return;
        flag = true;
        let count = 60; // 1分钟倒计时
        let timer = setInterval(function () {
            $('.CAPTCHA').text(`重新发送(${count})`);
            count--;
            if (count < 0) {
                flag = false;
                clearInterval(timer);
                $('.CAPTCHA').text('发送验证码');
            }
        }, 1000);
        showPrompt(data.module);
        localStorage.setItem('verificationCode', data.yzm);
    });
}

// 注册用户
function registerUser(account, password) {
    $.post(port + 'register', { account, password }, function (data) {
        data = JSON.parse(data);
        console.log(data);
        if (data.code == 0) {
            showPrompt(data.module);
            return;
        }
        localStorage.removeItem('verificationCode');
        showPrompt(data.module);
        $('#register').css('height', '0');
        $('#login').css('height', '100%');
        clearInput();
    });
}

// 登录判断
function setupLogin() {
    $('#loginBtn').click(function (e) {
        e.preventDefault();
        let account = $('#loginUsername').val();
        let password = $('#loginPassword').val();
        let errors = {
            username: $('#loginUsernameError'),
            password: $('#loginPasswordError')
        };
        if (validateInput(account, password, null, errors)) {
            loginUser(account, password);
        }
    });
}

// 登录用户
function loginUser(account, password) {
    $.post(port + 'login', { account, password }, function (data) {
        data = JSON.parse(data);
        if (data.code == 0) {
            showPrompt(data.module);
            return;
        }
        sessionStorage.setItem('userId', data.result[0].id);
        location.href = `${sxport}public/HTML/index.html?id=${data.result[0].id}`;
        $('.loginBox').css('height', '0');
        clearInput();
    });
}

// 显示提示信息
function showPrompt(message) {
    $('.promptBox').text(message).stop().animate({ 'width': '300px', 'height': '40px' }, 500, function () {
        $(this).animate({ width: '0', height: '0' }, 1000);
    });
}

// 输入验证函数
function validateInput(account, password, rVC, errors) {
    let isValid = true;
    if (account == '') {
        errors.username.text('用户名不能为空！');
        isValid = false;
    } else if (!isValidAccount(account)) {
        errors.username.text('请输入正确的手机号或邮箱!!!');
        isValid = false;
    } else {
        errors.username.text('');
    }
    if (password == '') {
        errors.password.text('密码不能为空！');
        isValid = false;
    } else if (password.length < 6) {
        errors.password.text('密码长度不能少于6位！');
        isValid = false;
    } else {
        errors.password.text('');
    }
    if (rVC !== null && rVC == '') {
        errors.verificationCode.text('验证码不能为空！');
        isValid = false;
    } else if (rVC !== null) {
        errors.verificationCode.text('');
    }
    return isValid;
}

// 验证账号格式
function isValidAccount(account) {
    const phone_regex = /^1[3-9]\d{9}$/;
    const email_regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return phone_regex.test(account) || email_regex.test(account);
}

// 验证是否为手机号
function isValidPhone(account) {
    const phone_regex = /^1[3-9]\d{9}$/;
    return phone_regex.test(account);
}